package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.utils.JwtUtils;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author 虎哥
 */
@EnableConfigurationProperties(ClientProperties.class)
@ConditionalOnProperty(prefix = "ly.auth", name = {"clientId", "secret"})
@EnableFeignClients("com.leyou.auth.client")
@Configuration
@Slf4j
public class AuthConfiguration {

    private AuthClient authClient;

    public AuthConfiguration(AuthClient authClient) {
        this.authClient = authClient;
    }

    @Bean
    public JwtUtils jwtUtils(ClientProperties properties, StringRedisTemplate redisTemplate){
        // 远程调用ly-auth，申请秘钥
        String key = null;
        while (true){
            try {
                key = authClient.getSecretKey(properties.getClientId(), properties.getSecret());
                break;
            } catch (FeignException e) {
                log.error("加载秘钥失败，原因：{}", e.contentUTF8());
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        log.info("加载秘钥成功！");
        return new JwtUtils(key, redisTemplate);
    }
}
